package com.attendcollatesys.excel.linstener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.util.ListUtils;
import com.attendcollatesys.entity.ATLeaveExtraDetail;
import com.attendcollatesys.ex.handler.ex.ExcelContentCheckException;
import com.attendcollatesys.service.ATLeaveExtraDetailService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.GZIPOutputStream;

/**
 * 加班请假sheet的监听器
 * add by gzl
 */
public class ExcelATLeaveExtraDetailListener extends AnalysisEventListener<ATLeaveExtraDetail> {

    /**
     * 每隔100条存储数据库
     */
    private static final int BATCH_COUNT = 100;

    private List<ATLeaveExtraDetail> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private ATLeaveExtraDetailService atLeaveExtraDetailService;

    private StringBuilder sheetHeadValue=new StringBuilder();

    private int count;


    private boolean checkFlag = false;

    public ExcelATLeaveExtraDetailListener(ATLeaveExtraDetailService atLeaveExtraDetailService) {
        this.atLeaveExtraDetailService=atLeaveExtraDetailService;
    }

    @Override
    public void invoke(ATLeaveExtraDetail atLeaveExtraDetail, AnalysisContext analysisContext) {
        //读取完表头就开始读取实际要录入的内容  此时需要校验的表头数据已全部拼装为一个字符串 这里再次压缩与先前压缩好的表头内容比对
        //项目为uft-8编码 选取其他编码格式 也会校验失败
//        if (!checkFlag) {
//            ByteArrayOutputStream baos = new ByteArrayOutputStream();
//            try (GZIPOutputStream gzipOut = new GZIPOutputStream(baos)) {
//                gzipOut.write(sheetHeadValue.toString().getBytes());
//            } catch (Exception e) {
//                throw new RuntimeException("文件头检查失败");
//            }
//
//            String sheetHeadCode="H4sIAAAAAAAAAM2ZXWsTQRSG/8tc5yJn851rP+iFRWoQe7m1sQQ2u7ImqIRcVOyHbWKCWnNhqaakRpSu1FZDUvpvOrvpvzB101ZTmCNHOZ273WGHfR/mDA9npiKiIlsRrvN4yp7PPxHZaETcd6xy0b54Lz19mBdZcSc3MzV9U0SEXS7O5d27plUeDdtly4qIRyW3YC+Mh4Rc+xA0dodfe3JxZfT9nONYedP+Y8K8WTLPnh84brFsmdd+G3LcwkLBNq3py786nXljNMMsXUyoRgSoMeAc4/qt27nZv6AIh1iyG+rshs7ZY+rsMZ2zx9XZ4zpnT6izJ3TOnlRnT+qcPaXOntI5e1qdPa1z9ow6e0bn7IA4FqJap8fUqrVbAZEraG1XQPQKWvsVEMGC1oYFRLGgtWMBkSxobVlANAtaexYQ0YLWpgVEtaC1aw3EtYbGrq1WJrtx4z9048Gb/dNWvL4hG70r6sYnMYCAMdz+EpIcDwayt8MIY6hhDMoJSeetrC3J7mvZrHNhxNQYMQLGTO7e8OAj41LE1QxxylIcvZJ7W/LlM7mxzIWRUGMkKBjfWsdHbLWUVAMkKft7sRYMulwAKTVAigDgb9blWlt2nkuvw4WRVmOkCRgn7X7wzgsOG0GTbT9k1BgZsvWCvUO5tc5mPcTeQNH38HtPdtf91o6/+Z4NBPM3ReDjW4Exzo+T1gEbDmJwoCg8vN4IcZjLDDE5UFTur372d7eZywzROZB8/qvMpFfzV5vMZYZoHSheD8ssXB3mMkMkDxTLy86Kv/+JDQHRPFA8f96FsFEglgeK5kMK5g2CeB4oopde23/Rv4r9PnnUcKkx/IdufXlJen0ekOpP8qGvngQgAAA=";
//            if(!Base64.getEncoder().encodeToString(baos.toByteArray()).equals(sheetHeadCode)){
//                System.out.println(Base64.getEncoder().encodeToString(baos.toByteArray()));
//              // throw new ExcelContentCheckException("加班请假表表头数据与预期不符");
//            }
//            checkFlag=!checkFlag;
//        }

        cachedDataList.add(atLeaveExtraDetail);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 此方法会读取前表头内容
     */
//    @Override
//    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
//        ObjectMapper objectMapper = new ObjectMapper();
//        count++;
//        if(count==2)return;//导出人不用检验内容
//        try {
//            sheetHeadValue.append(objectMapper.writeValueAsString(headMap));
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException("文件头解析失败");
//        }
//
//    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (cachedDataList.size() > 0) {
            saveData();
        }
        System.out.println("加班请假sheet导入完毕");
    }

    private void saveData(){
        List<String> requestNoList = cachedDataList.stream()
                .map(ATLeaveExtraDetail::getRequestNumber)
                .collect(Collectors.toList());

        atLeaveExtraDetailService.deleteByRequestNo(requestNoList);
        atLeaveExtraDetailService.insertBatch(cachedDataList);
    }
}
